package com.ts.service.achievement.impl;

import com.ts.dto.HonorsAwardDTO;
import com.ts.entity.TeacherHonors;
import com.ts.mapper.achievement.TeacherHonorsMapper;
import com.ts.service.achievement.TeacherHonorsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeacherHonorsServiceImpl implements TeacherHonorsService {

    @Autowired
    private TeacherHonorsMapper teacherHonorsMapper;

    /**
     * 提交一个荣誉获奖成果
     * @param honorsAwardDTO
     */
    @Override
    @Transactional
    public void save(HonorsAwardDTO honorsAwardDTO) {
        // 1. 实体类对象拷贝
        TeacherHonors teacherHonors = new TeacherHonors();
        BeanUtils.copyProperties(honorsAwardDTO, teacherHonors);

        // 2. 手动添加公共字段
        teacherHonors.setCreateTime(LocalDateTime.now());
        teacherHonors.setUpdateTime(LocalDateTime.now());
        teacherHonors.setCreateBy(1L);
        teacherHonors.setUpdateBy(1L);

        // 3. 调用Mapper接口
        teacherHonorsMapper.save(teacherHonors);
    }
    @Override
    @Transactional
    public void update(HonorsAwardDTO honorsAwardDTO) {
        TeacherHonors teacherHonors = new TeacherHonors();
        BeanUtils.copyProperties(honorsAwardDTO, teacherHonors);

        teacherHonors.setUpdateTime(LocalDateTime.now());
        teacherHonors.setUpdateBy(1L);

        teacherHonorsMapper.update(teacherHonors);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        teacherHonorsMapper.delete(id);
    }

    @Override
    public HonorsAwardDTO getById(Long id) {
        TeacherHonors teacherHonors = teacherHonorsMapper.getById(id);
        if (teacherHonors == null) {
            return null;
        }
        HonorsAwardDTO honorsAwardDTO = new HonorsAwardDTO();
        BeanUtils.copyProperties(teacherHonors, honorsAwardDTO);
        return honorsAwardDTO;
    }

    @Override
    public List<HonorsAwardDTO> listAll() {
        List<TeacherHonors> honorsList = teacherHonorsMapper.listAll();
        return honorsList.stream().map(teacherHonors -> {
            HonorsAwardDTO dto = new HonorsAwardDTO();
            BeanUtils.copyProperties(teacherHonors, dto);
            return dto;
        }).collect(Collectors.toList());
    }
}
